/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ext;

import com.ptc.core.components.beans.CreateAndEditWizBean;
import com.ptc.core.components.descriptor.ComponentDescriptor;
import com.ptc.core.components.descriptor.DataUtility;
import com.ptc.core.components.descriptor.DataUtilityHelper;
import com.ptc.core.components.descriptor.DescriptorHelper;
import com.ptc.core.components.descriptor.JCAObject;
import com.ptc.core.components.descriptor.ModelContext;
import com.ptc.core.components.factory.AbstractDataUtility;
import com.ptc.core.components.factory.dataUtilities.AttributeDataUtilityHelper;
import com.ptc.core.components.factory.dataUtilities.StringGuiComponentFactory;
import com.ptc.core.components.rendering.guicomponents.ComboBox;
import com.ptc.core.components.rendering.guicomponents.GUIComponentArray;
import com.ptc.core.components.rendering.guicomponents.GuiComponentUtil;
import com.ptc.core.components.rendering.guicomponents.PushButton;
import com.ptc.core.components.rendering.guicomponents.TextArea;
import com.ptc.core.components.rendering.guicomponents.TextBox;
import com.ptc.core.components.rendering.guicomponents.TextDisplayComponent;
import com.ptc.core.meta.common.TypeInstanceIdentifier;
import com.ptc.core.ui.resources.ComponentMode;
import com.ptc.netmarkets.util.beans.NmCommandBean;
import ext.generic.util.IBAUtility;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import java.util.Vector;
import org.apache.commons.lang.StringUtils;
import wt.doc.WTDocument;
import wt.httpgw.URLFactory;
import wt.type.TypedUtilityServiceHelper;
import wt.util.WTException;

/**
 *
 * @author JosephCC_Chen
 */
public class MultiDataUtilityDemo extends AbstractDataUtility {

    String displayId = "";
    String keyId = "";

    @Override
    public Object getDataValue(String component_id, Object datum, ModelContext mc)
            throws WTException {
        System.out.println("into Ext_PCBAgentDataUtility.getDataValue()...");
        System.out.println("component_id = " + component_id);
        //System.out.println("datum = " +datum);
        //System.out.println("mc = " + mc.getTargetObjectKey());
        //System.out.println("mc2 = " + mc.getJCAObject().getBackingObject());
        Random ra = new Random(System.currentTimeMillis());
        long dd = Math.round(ra.nextDouble() * 100000000);
        System.out.println("dd=" + dd);
        displayId = component_id + dd + "_multi_Disp";
        keyId = component_id + dd + "_KEY";
        GUIComponentArray componentArray = new GUIComponentArray();
        String last = component_id.substring(component_id.lastIndexOf("|") + 1, component_id.length());
        System.out.println("last = " + last);
        ComponentDescriptor descriptor = DescriptorHelper.getDescriptor(last);

        // Object ootbDU = DataUtilityHelper.getDataUtility(descriptor).getDataValue(component_id, datum, mc);
//        Object ootbDU = DataUtilityHelper.getDefaultDataValue(component_id, datum, mc);
        System.out.println("mc.getDescriptorMode() = " + mc.getDescriptorMode());
        if (mc.getDescriptorMode().equals(ComponentMode.VIEW)) {
            //can't return ooTB Datautility due to unlimite loop
            return DataUtilityHelper.getDataUtility(DescriptorHelper.getDescriptor("name")).getDataValue(component_id, datum, mc);
        }
        try {

            String objType = "";
            NmCommandBean clientData = mc.getNmCommandBean();
            if (mc.getDescriptorMode().equals(ComponentMode.CREATE)) {//理論上在建立時不會出現
                TypeInstanceIdentifier tiid = CreateAndEditWizBean.getItemTypeInstanceId(clientData);
                objType = tiid.toString();
            } else if (mc.getDescriptorMode().equals(ComponentMode.EDIT)) {
                //System.out.println("++++++++++ mc.getJCAObject() = " + mc.getJCAObject());
                JCAObject object = mc.getJCAObject();
                objType = object.getBaseType().getTypename();
            }
            //for display
            //shit for IE8, select is fail, so use text area
            /*
            ComboBox cb = new ComboBox();
            cb.setId(displayId);
            cb.setColumnName(AttributeDataUtilityHelper.getColumnName(component_id, datum, mc) + "_multi_Disp");
            cb.setLabel(getLabel(component_id, mc));
            cb.setEditable(true);
            cb.addStyleClass("ExtMultiDisplayClass");
             * 
             */
            TextArea cb = new TextArea();
            cb.setId(displayId);
            cb.setColumnName("XXXCUSTOMIZEXXX" + dd + "_multi_Disp");

            cb.setEditable(true);
            cb.addStyleClass("ExtMultiDisplayClass");
            //key
            TextBox tb = createTextBox(mc, "");
            tb = setTextBoxProperties(tb, component_id, datum, mc);
            tb.setReadOnly(false);
            tb.setEnabled(true);
            tb.setEditable(true);
            tb.addStyleClass("ExtHiddenClass");
            System.out.println("************** start ***************");
            PushButton findButton = createGetDataButton(mc, component_id, displayId);
            System.out.println("************** end ***************");
            if (mc.getDescriptorMode().equals(ComponentMode.EDIT)) {
                WTDocument wtd = null;
                if (CreateAndEditWizBean.getEditObjectReference(clientData) != null) {
                    wtd = (WTDocument) CreateAndEditWizBean.getEditObjectReference(clientData).getObject();
                } else {
                    wtd = (WTDocument) datum;
                }
                if (wtd == null) {
                    TextDisplayComponent tdc = new TextDisplayComponent("ff");
                    tdc.setColumnName(AttributeDataUtilityHelper.getColumnName(component_id, datum, mc) + "_multi_Disp");
                    tdc.setValue("Can't get WTDocument!!");
                    componentArray.addGUIComponent(tdc);
                    return componentArray;
                }
                IBAUtility iba = new IBAUtility(wtd);

                //System.out.println("########## pcbType = " + pcbType);

                String typeName = TypedUtilityServiceHelper.service.getExternalTypeIdentifier(wtd); //WTTYPE|

                String attrName = component_id.substring(component_id.indexOf("|") + 1, component_id.length());
                //System.out.println("########## attrName = " + attrName);
                Vector vals = iba.getIBAValues(attrName);
                if (vals != null && vals.size() > 0) {

                    //ReadPropertyUtil propertyUtil = new ReadPropertyUtil("ext\\ext.properties");
                    //String separate = propertyUtil.getValue(typeName + "~IBA|" + attrName + ".MultiValue.Separate");
                    ArrayList internalV = new ArrayList();
                    StringBuffer sb = new StringBuffer();


                    for (int i = 0; i < vals.size(); i++) {
                        internalV.add(vals.get(i));
                        sb.append((String) vals.get(i));
                        if (i < vals.size() - 1) {
                            sb.append(",");
                        }
                    }
                    cb.setValue(sb.toString());
                    tb.setValue(sb.toString());
                }
                //button

                System.out.println("########## vals = " + vals);
            } else if (mc.getDescriptorMode().equals(ComponentMode.CREATE)) { //edit mode
            }


            componentArray.addGUIComponent(cb);
            componentArray.addGUIComponent(tb);
            componentArray.addGUIComponent(findButton);
            componentArray.setRequired(AttributeDataUtilityHelper.isInputRequired(mc));

        } catch (Exception e) {
            //TextDisplayComponent tdc = new TextDisplayComponent("");
            //tdc.setColumnName(AttributeDataUtilityHelper.getColumnName(component_id, datum, mc) + "_multi_Disp");
            //tdc.setValue(e.getLocalizedMessage());
            //componentArray.addGUIComponent(tdc);
            e.printStackTrace();
        }
        //System.out.println("exit Ext_PCBAgentDataUtility.getDataValue()...");
        return componentArray;
        //return ootbDU;
    }

    public TextBox createTextBox(ModelContext mc, String val) throws WTException {
        int width = GuiComponentUtil.TEXT_INPUT_WIDTH;
        int maxStringLength = StringGuiComponentFactory.getMaxStringLength(mc.getDescriptor(), mc.getJCAObject(), mc);
        if ((maxStringLength > 0) && (maxStringLength < GuiComponentUtil.TEXT_INPUT_WIDTH)) {
            width = maxStringLength;
        }
        TextBox textBox = GuiComponentUtil.createTextBox(width, maxStringLength);
        if (StringUtils.isNotEmpty(val)) {
            textBox.setValue(val);
        }
        return textBox;
    }

    public PushButton createGetDataButton(ModelContext mc, String component_id, String displayElementId)
            throws WTException {
        PushButton findButton = new PushButton("");
        findButton.setName("Search");
        findButton.setLabel("Search");
        //findButton.setId(component_id + "button");
        URLFactory urlfactoryc = new URLFactory();
        URL url = urlfactoryc.getURL("netmarkets/jsp/ext/MultiChoosePage.jsp", new HashMap());
        findButton.addJsAction("onClick", "javascript:wfWindowOpen('" + url + "?displayElementId=" + displayElementId + "&component_id=" + keyId + "','SearchModelNameWin','toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,copyhistory=yes,top=50,left=300,width=865,height=395');");
        return findButton;
    }

    public TextBox setTextBoxProperties(TextBox nInput, String component_id, Object datum, ModelContext mc) throws WTException {
        nInput.setId(keyId);
        nInput.setColumnName(AttributeDataUtilityHelper.getColumnName(component_id, datum, mc));
        //nInput.setLabel(getLabel(component_id, mc));
        nInput.setEditable(true);
        nInput.setRequired(AttributeDataUtilityHelper.isInputRequired(mc));
        return nInput;
    }
}
